//
//  FirstViewController.m
//  PrayerTimes
//
//  Created by Igor Karpenko on 6/8/13.
//  Copyright (c) 2013 Igor Karpenko. All rights reserved.
//

#import "CompassViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "DataProvider.h"

#import "JBTabBarController.h"
#import "ChangeCityViewController.h"

@interface CompassViewController ()

@property(nonatomic, retain) CLLocationManager *locationManager;

@end


@implementation CompassViewController


#pragma mark - Instance initialization

-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self) {
		return nil;
    }
	mecca = CLLocationCoordinate2DMake(21.43261686447735, 39.814453125);
	
	self.title = NSLocalizedString(@"Compass", nil);
	self.tabBarItem.image = [UIImage imageNamed:@"gnr_compassIcon"];
	self.tabBarItem.selectedImage = [UIImage imageNamed:@"gnr_compassIcon_active"];
	
	return self;
}



#pragma mark - Memory managment

-(void) dealloc {
	[_locationManager release];
	
	[_meccaButton release];
	[_compassArrowsImage release];
	[_qiblaImage release];
	[_backgroundImage release];
	[_frameImage release];
	
	[_infoLabel release];
	[super dealloc];
}


#pragma mark - Interface methods

-(void) viewDidLoad {
    [super viewDidLoad];

	firstUpdate = YES;
	_meccaButton.alpha = 0.3;
	_frameImage.image = [_frameImage.image resizableImageWithCapInsets:UIEdgeInsetsMake(230.0f, 0.0f, 20.0f, 0.0f)];
}


-(void) viewDidUnload {
	[self setMeccaButton:nil];
	[self setCompassArrowsImage:nil];
	[self setQiblaImage:nil];
	[self setBackgroundImage:nil];
	[self setFrameImage:nil];

	[self setInfoLabel:nil];
	[super viewDidUnload];
}


-(void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self changeLanguage];
}


-(void) viewDidAppear: (BOOL)animated {
	[super viewDidAppear:animated];
	
	if ([DataProvider sharedInstance].currentCountry == nil) {
		ChangeCityViewController *controller = [[ChangeCityViewController alloc] initWithNibName:@"ChangeCityViewController"
																						  bundle:nil];
		
		
		UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
		[rootViewController presentViewController:controller
										  animated:YES
										completion:nil];
		[controller release];
		return;
	}
	
	DataProvider *dataProvider = [DataProvider sharedInstance];
	CLLocationCoordinate2D coordinates = CLLocationCoordinate2DMake([dataProvider.latitude doubleValue], [dataProvider.longitude doubleValue]);
	qiblaAngle = -[self getDirectionFromPoint:coordinates toPoint:mecca];
	
	[UIView animateWithDuration:1 animations:^{
		_qiblaImage.transform = CGAffineTransformMakeRotation(qiblaAngle);
	} completion:^(BOOL finished) {
		BOOL headingAvailable = [CLLocationManager headingAvailable];
		
		if (!headingAvailable) {
			_infoLabel.hidden = NO;
			return;
		}
		
		_locationManager=[[CLLocationManager alloc] init];
		_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
		_locationManager.headingFilter = 0.5f;
		_locationManager.delegate = self;
		[_locationManager startUpdatingHeading];
	}];
}


#pragma mark - Private methods

-(double) getDirectionFromPoint:(CLLocationCoordinate2D)fromPoint
									 toPoint:(CLLocationCoordinate2D)toPoint {
	double dLongitude = [self deegreeToRadian:fromPoint.longitude - toPoint.longitude];
	double lat1 = [self deegreeToRadian:fromPoint.latitude];
	double lat2 = [self deegreeToRadian:toPoint.latitude];
	
	double resultInRadians = atan2(sin(dLongitude), cos(lat1) * tan(lat2) - sin(lat1) * cos(dLongitude));
	return resultInRadians;
}


-(double) deegreeToRadian:(CGFloat)degree {
	return (degree * M_PI) / 180.0f;
}


-(double) radianToDeegree:(CGFloat)radian {
	return (radian * 180.0f) / M_PI;
}


-(void) changeLanguage {
	[_meccaButton setTitle:AMLocalizedString(@"mecca", nil) forState:UIControlStateNormal];
}


#pragma mark - Delegated methods

-(void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
	float newRad = -newHeading.trueHeading * M_PI / 180.0f;
	if (-newRad <= qiblaAngle + 0.034 && -newRad >= qiblaAngle - 0.034) {
		_meccaButton.alpha = 1.0;
	} else {
		_meccaButton.alpha = 0.3;
	}

	
	if (firstUpdate) {
		[UIView animateWithDuration:0.5f animations:^{
			_compassArrowsImage.transform = CGAffineTransformMakeRotation(newRad);
		}];
		firstUpdate = NO;
		return;
	}
	_compassArrowsImage.transform = CGAffineTransformMakeRotation(newRad);
}


-(BOOL) locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager {
	return YES;
}

@end
